// index.js
// 获取应用实例
const app = getApp()

// pages/home/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    tabbarList: app.globalData.tabbarList,

    swiperList: [
      {
        url: '/picture/1.jpg'
      }, 
      {
        url: '/picture/2.jpg'
      }, 
      {
        url: '/picture/3.jpg'
      }, 
      {
        url: '/picture/4.jpg'
      }, 
      {
        url: '/picture/5.jpg'
      }
    ],
    articleList: [],
    inputValue: ''
  },

  // 点击 + 号
  onClickPublish(event) {
    console.log("onClickPublish");
    wx.navigateTo({
      url: '/pages/home/publish/publish',
    });
  },

  onInput(event) {
    console.log("onInput", event);
    this.setData({ 
      inputValue: event.detail
    });
  },

  // 点击搜索按钮
  onClickSearch(event) {
    console.log("onClickSearch", event);

    let articleList = this.data.articleList;
    let flag = this.data.inputValue;
    let tempList = [];
    for (var i = 0; i < articleList.length; i++) {
      var title = articleList[i].title;
      var content = articleList[i].content;
      if (title.includes(flag) || content.includes(flag)) {
        tempList.push(articleList[i]);
      }
    }

    this.setData({
      articleList: tempList,
      inputValue: ''
    });
  },

  onClickTabbar(event) {
    console.log("onClickTabbar", event);
    const url = this.data.tabbarList[event.detail].url;

    wx.switchTab({
      url: url,
    });
  },

  // 点击文章
  onClickArticle(event) {
    console.log("onClickArticle", event);

    let article = event.currentTarget.dataset.item;
    article.viewCount += 1;
    console.log("article", article);

    wx.cloud.callFunction({
      name: 'update_article',
      data: {
        article: article
      },
      success: res => {
        console.log("update article success", res);
      },
      fail: res => {
        console.log("update article fail", res);
      }
    })


    wx.navigateTo({
      url: '/pages/home/article/article?article=' + encodeURIComponent(JSON.stringify(article)),
    })
  },

  // 调用云函数 get_article
  getArticle: function() {
    wx.showLoading({
      title: '数据加载中',
    });

    var that = this;
    wx.cloud.callFunction({
      name: "get_article",
      success: res => {
        console.log("get_article success", res);

        that.setData({
          articleList: res.result.data
        });

        console.log("articleList", that.data.articleList);
        wx.hideLoading();
      },
      fail: res => {
        console.log("get_article fail", res);
        wx.hideLoading();
      }
    });
  },

  // 生命周期函数--监听页面初次渲染完成
  onLoad(options) {
    this.getArticle();
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() { },

  // 生命周期函数--监听页面显示
  onShow() { },

  // 生命周期函数--监听页面隐藏
  onHide() { },

  // 生命周期函数--监听页面卸载
  onUnload() { },

  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() {
    this.getArticle();
  },

  // 页面上拉触底事件的处理函数
  onReachBottom() { },

  // 用户点击右上角分享
  onShareAppMessage() { }
})